<template>
  <div class="chat-container">
    <el-card class="chat-card">
      <template #header>
        <div class="card-header">
          <h2>七鱼-AI</h2>
          <el-select v-model="selectedModel" placeholder="选择模型" @change="handleModelChange">
            <el-option
              v-for="model in models"
              :key="model.id"
              :label="model.name"
              :value="model.id"
            />
          </el-select>
        </div>
      </template>

      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
        >
          <div class="message-avatar">
            <el-avatar :icon="message.role === 'user' ? 'UserFilled' : 'Service'" />
          </div>
          <div class="message-content">
            <div class="message-role">{{ message.role === 'user' ? '用户' : 'AI助手' }}</div>
            <div class="message-text">
              <div v-highlight v-html="message.content"></div>
            </div>
          </div>
        </div>
        <div v-if="loading" class="loading-indicator">
          <el-icon class="is-loading"><Loading /></el-icon> AI正在思考...
        </div>
      </div>

      <div class="chat-input">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          @keyup.enter.ctrl="sendMessage"
        />
        <div class="input-actions">
          <el-button type="primary" :disabled="loading || !userInput.trim()" @click="sendMessage">
            发送 <el-icon class="el-icon--right"><Position /></el-icon>
          </el-button>
          <el-button @click="clearChat" :disabled="loading || messages.length === 0">
            清空对话 <el-icon class="el-icon--right"><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'
import { marked } from 'marked'

// 响应式状态
const userInput = ref('')
const messages = ref([])
const loading = ref(false)
const models = ref([])
const selectedModel = ref('')
const messagesContainer = ref(null)

// import markdown from './data'
const markdownToHtml = ref(null)
const mdToHtml = (item) => {
  return marked(item)
}
// messages.value.push(markdownToHtml)
// 获取模型列表
const fetchModels = async () => {
  try {
    const response = await api.getModels()
    models.value = response.data || []
    if (models.value.length > 0) {
      selectedModel.value = models.value[0].id
    }
  } catch (error) {
    ElMessage.error('获取模型列表失败')
    console.error('获取模型列表失败:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return

  // 添加用户消息
  const userMessage = userInput.value.trim()
  messages.value.push({ role: 'user', content: userMessage })
  userInput.value = ''

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 发送到API
  loading.value = true
  const aaa = {
    model: selectedModel.value,
    messages: messages.value.map((msg) => ({
      role: msg.role,
      content: msg.content,
    })),
  }

  console.log(aaa)

  try {
    const response = await api.sendChatMessage({
      model: selectedModel.value,
      messages: messages.value.map((msg) => ({
        role: msg.role,
        content: msg.content,
      })),
    })

    console.log('=====>', response.data.choices[0].message)
    // markdownToHtml.value = marked(response.data.choices[0].message.content)
    // 添加AI回复
    // if (response && response.data && response.data.content) {
    messages.value.push({
      role: 'assistant',
      content: mdToHtml(response.data.choices[0].message.content),
    })

    console.log(messages.value)
    // } else {
    //   throw new Error('无效的响应格式')
    // }
  } catch (error) {
    ElMessage.error('发送消息失败')
    console.error('发送消息失败:', error)
  } finally {
    loading.value = false
    await nextTick()
    scrollToBottom()
  }
}

// 清空对话
const clearChat = () => {
  messages.value = []
}

// 模型变更处理
const handleModelChange = (value) => {
  console.log('选择的模型:', value)
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 监听消息变化，自动滚动
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 组件挂载时获取模型列表
onMounted(() => {
  fetchModels()
})
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.chat-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

h2 {
  width: 100px;
}
.card-header h2 {
  margin: 0;
  color: #409eff;
}

.chat-messages {
  height: 500px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 20px;
}

.message {
  display: flex;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.message-content {
  background-color: #fff;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  max-width: 80%;
}

.user-message .message-content {
  background-color: #ecf5ff;
}

.ai-message .message-content {
  background-color: #f0f9eb;
}

.message-role {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-text {
  white-space: pre-wrap;
  word-break: break-word;
  min-height: 20px;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 10px;
}

.chat-input {
  margin-top: 10px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}
</style>
